//
//  HomeViewController.m
//  NavZe
//
//  Created by ZengYuan on 15/8/3.
//  Copyright (c) 2015年 ZengYuan. All rights reserved.
//

#import "HomeViewController.h"
#import "EScrollerView.h"
#import "HomeCookCell.h"
#import "HomeEsView.h"
#import "ShowItemCell.h"
#import "RouteUnit.h"
#import "UserLogin.h"
#import "DeviceUnit.h"
#import "MonitorListViewController.h"
#import "KxMenu.h"
#import "QRCodeViewController.h"
#import "WebViewController.h"
#import "InputDeviceViewController.h"
#import "ChannelUnit.h"
#import "SmartDeviceViewCell.h"

#import "MonitorViewController.h"
#import "DeviceInfoViewController.h"
#import "AppDelegate.h"

//#define AD_HEIGHT 150.f

@interface HomeViewController ()
{
    EScrollerView *esview;
    NSMutableArray *ads;
    
    CGFloat AD_height;
}
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.titleLabel.text=@"首页";

    CGRect rec = self.tableView.frame;
    rec.size.height = kScreenHeight - NAVBARHEIGHT_STATUSBAR - self.tabBarController.tabBar.frame.size.height;
    self.tableView.frame=rec;

    //存储屏幕Portrait状态下的标准尺寸
    [[NSUserDefaults standardUserDefaults] setFloat:kScreenWidth forKey:@"Portrait_kScreenWidth"];
    [[NSUserDefaults standardUserDefaults] setFloat:kScreenHeight forKey:@"Portrait_kScreenHeight"];
    
    
    // Do any additional setup after loading the view.
    self.titleLabel.text=@"我的产品";
    AD_height = kScreenWidth /(2.61);
    
    __weak __typeof(self)weakSelf = self;

    if(self.needLogin){
        UserUnit *user = [UserUnit getActiveUser];
        if(user.userPhone && user.userPasswd){
            
            [UserLogin loginBy:user.userPhone andPwd:user.userPasswd success:^{
                [weakSelf getADs];
                [weakSelf getData];
            } failure:^(NSString *error) {
//                MBALERT(@"登录失败");
                
                AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                [delegate returnLoginContrller];
            }];
        }

    }else{
        [self getADs];
        [self getData];
    }
    
    
    [self.rightBtnPar setTitle:@"添加" forState:UIControlStateNormal];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(freshNoti) name:KHOME_FRESH_DEVICELIST_NOTI object:nil];
}

-(void)freshNoti{
    [self getData];
}

-(void)getData{

    Reachability*rea= [Reachability reachabilityForInternetConnection];
    //网络连接失败
    if (![rea isReachable]){
        
        if (fullloadingView) {
            [fullloadingView showErrorMsg:HTTPERROR_CANNOTREACH];
            [self doneLoadingTableViewData];
            
        }else{
            MBALERT(HTTPERROR_CANNOTREACH);
            [self doneLoadingTableViewData];
        }
        return;
    }
    
    page = 1;
    freshPos=EGORefreshHeader;
    [self getListData];
}

/**
 *  上拉获取更多
 */
-(void)getMoreData{
    Reachability*rea= [Reachability reachabilityForInternetConnection];
    if (![rea isReachable]){
        MBALERT(HTTPERROR_CANNOTREACH);
        return;
    }
    
    page++;
    freshPos=EGORefreshFooter;
    [self getListData];
}
-(void)getListData{
    
     
    NSString *url = [NSString stringWithFormat:MAINURL, URL_GETDEVICES];
    __unsafe_unretained typeof(self) weakSelf = self;

    
    NSString *sid = [[NSUserDefaults standardUserDefaults] objectForKey:@"session_id"];
    
    if(!sid)return;
    
    NSDictionary *dic = [[NSDictionary alloc] initWithObjects: @[sid] forKeys:@[@"session_id"]];
    NSString *json  =[dic JSONString];

    [AWHttpTool post:url body:json success:^(id json) {
        if (json) {
            [self doneLoadingTableViewData];
            NSInteger sta = [json[@"status"] integerValue];
            NSLog(@"json=%@", json);
            if (sta == 0) {

                NSArray *devices = json[@"devices"];

                NSMutableArray *tempArray = [SmartDeviceUnit objectArrayWithKeyValuesArray:devices];

                if (freshPos== EGORefreshHeader) {
                    self.dataArray = [NSMutableArray array];
                }else{
                }
                
                [self.dataArray addObjectsFromArray:tempArray];
                [weakSelf.tableView reloadData];
                
            }else{
                NSString *err = json[@"msg"];
                MBALERT(err);
            }
        }
    } failure:^(NSError *error) {
        //        [hud hide:YES afterDelay:0.5];
        [self doneLoadingTableViewData];

        MBALERT(HTTPERROR_DATAFAIL);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1 +  (self.dataArray.count?1:0);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0)
        return AD_height;

    return 99;
}


- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if(indexPath.section == 0){
        
        static NSString *CellId_ES = @"CellIdEs";
        SettingCell *cell=[_tableView dequeueReusableCellWithIdentifier:CellId_ES];
        if (!cell) {
            cell=[[SettingCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellId_ES];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor=[UIColor whiteColor];
            cell.rowType = 3;
            
            esview = [[EScrollerView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, AD_height)];
            [cell addSubview:esview];
            esview.delegate=self;
        }
        
        if(ads.count>0){
            [esview reloadData:ads];
        }
        
//        RouteUnit *route = self.dataArray[indexPath.row];
//        cell.nameLabel.text = route.router_name;
        return cell;
    }else{
        
        SmartDeviceViewCell *cell = [SmartDeviceViewCell cellWithTableView:self.tableView];
        SmartDeviceUnit *smartdevice = self.dataArray[indexPath.row];
        cell.nameLabel.text =smartdevice.device_name;

        cell.channelCountLabel.text = [NSString stringWithFormat:@"%ld", (long)smartdevice.device_channel_num];
        
        cell.userCountLabel.text = [NSString stringWithFormat:@"%ld", (long)smartdevice.shared_user_count];
        
        cell.rowType = 3;
        
        
        __weak typeof(self) weakSelf = self;

        cell.tapBlock=^{

            DeviceInfoViewController *divc = [[DeviceInfoViewController alloc]init];
            divc.sdevice = smartdevice;
            divc.unbindBlock=^(){
                [weakSelf getData];
            };
            divc.hidesBottomBarWhenPushed=YES;
            [weakSelf.navigationController pushViewController:divc animated:YES];
        };
        return cell;
    }
   
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)_tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section > 0) {
    
        MonitorListViewController *mlvc = [[MonitorListViewController alloc]init];
        
        SmartDeviceUnit *sdu = self.dataArray[indexPath.row];
        mlvc.device_unit = sdu;

        mlvc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:mlvc animated:YES];
 
    }
}

-(void)EScrollerViewDidClicked:(NSUInteger)index{
    
    WebViewController *wvc = [[WebViewController alloc]init];
    wvc.hidesBottomBarWhenPushed=YES;
    wvc.url = @"http://jia.mall.360.com/";
    [self.navigationController pushViewController:wvc animated:YES];
}


-(void)navRightAction{
    
    NSArray *menuItems =
    @[

      [KxMenuItem menuItem:@"扫一扫"
                     image:[UIImage imageNamed:@"home_icon"]
                    target:self
                    action:@selector(pushMenuItem:)],
      
      [KxMenuItem menuItem:@"手动输入"
                     image:[UIImage imageNamed:@"search_icon"]
                    target:self
                    action:@selector(pushMenuItem:)],

      ];
    
//    KxMenuItem *first = menuItems[0];
//    first.foreColor = [UIColor colorWithRed:47/255.0f green:112/255.0f blue:225/255.0f alpha:1.0];
//    first.alignment = NSTextAlignmentCenter;
    
    [KxMenu showMenuInView:self.view
                  fromRect:self.rightBtnPar.frame
                 menuItems:menuItems];

    
}

- (void) pushMenuItem:(id)sender
{
    NSLog(@"%@", sender);
    
    KxMenuItem *item = sender;
    if ([item.title isEqualToString:@"扫一扫"]) {
        
        QRCodeViewController *qrvc = [[QRCodeViewController alloc]init];
        qrvc.hidesBottomBarWhenPushed=YES;

        [self.navigationController pushViewController:qrvc animated:YES];
        
    }else{
        
        UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        InputDeviceViewController *irvc = [board instantiateViewControllerWithIdentifier:@"inputlvc"];
        irvc.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:irvc animated:YES];
        
    }
    
}


//获取广告位
-(void)getADs{
    
    NSString *url = [NSString stringWithFormat:MAINURL, URL_GETADS];
    __unsafe_unretained typeof(self) weakSelf = self;
    
    NSString *sid = [[NSUserDefaults standardUserDefaults] objectForKey:@"session_id"];
    
    if(!sid)return;
    
    NSDictionary *dic = [[NSDictionary alloc] initWithObjects: @[sid] forKeys:@[@"session_id"]];
    NSString *json  =[dic JSONString];
    
    [AWHttpTool post:url body:json success:^(id json) {
        if (json) {
            
            NSInteger sta = [json[@"status"] integerValue];
            NSString *err = json[@"msg"];
            
            if (sta == 0) {
                
                NSArray *home_advertisings = json[@"advertisings"];
                ads = [NSMutableArray array];
                
                for(int i=0; i<home_advertisings.count; i++){
                    NSDictionary *dic = home_advertisings[i];
                    
                    ShowUnit *showunit = [[ShowUnit alloc]init];
                    showunit.picurl = dic[@"img"];
                    showunit.atitle = dic[@"title"];
                    showunit.contentUrl = [SystemUtils revertQNBigUrl: dic[@"url"]];
                    
                    
                    [ads addObject:showunit];
                }
                [weakSelf.tableView reloadData];
                
            }else{
                NSLog(@"********ad = %@",err);

//
//                MBALERT(err);
            }
        }
    } failure:^(NSError *error) {
        NSLog(@"********ad = %@",error);
        
        //        [hud hide:YES afterDelay:0.5];
//        [self doneLoadingTableViewData];
        
//        MBALERT(HTTPERROR_DATAFAIL);
    }];

    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
